package com.cy.pj.ajax.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
public class AjaxController {
//假设这是数据库中的表
    private List<Map<String,Object>> list= new ArrayList<>();

    public AjaxController(){//构建对象时，在构造方法中初始化一部分数据
        Map<String,Object> map= new HashMap<>();
        map.put("id","100");
        map.put("name","华为");
        map.put("remark","Very good");
        list.add(map);
    }
    @PutMapping("doAjaxPut")
    @ResponseBody
    public String doAjaxPut(@RequestParam Map<String,Object> map){
        String id = (String) map.get("id");
        Iterator<Map<String, Object>> it = list.iterator();
        Map<String, Object> obj=null;
        while (it.hasNext()){
            obj = it.next();
            if(obj.get("id").equals(id))break;
        }
        obj.put("name",map.get("name"));
        obj.put("remark",map.get("remark"));
//        for(Map<String,Object> item:list){
//            if(item.get("id").equals(id)){
//                item.put("name",map.get("name"));
//                item.put("remark",map.get("remark"));
//            }
//        }

        return "update ok";
    }
    @ResponseBody
    @DeleteMapping("/doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable Integer id){
//        ??????????怎么删除呢---获取迭代器
        Iterator<Map<String, Object>> it = list.iterator();
        while (it.hasNext()){
            Map<String, Object> map=it.next();
            if(map.get("id").equals(String.valueOf(id))){
                it.remove();//用迭代器删除
//                list.remove(map);//不可以这样删除，有迭代异常
            }
        }
        return "delete ok";
    }


    @PostMapping("/doAjaxPost")
    @ResponseBody
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        list.add(map);
        return "save ok";
    }
    @CrossOrigin//此注解描述的方法运行跨域访问

    @GetMapping("/doAjaxGet")// 注解描述是方法只能处理get请求方式的映射
//    @RequestMapping(value = "/doAjaxGet",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object>> doAjaxGet(){
        return list;
    }
    //===========传统方式的页面请求=================
    @RequestMapping("/doNotAjaxUI")
    public String doNotAjaxUI(){
        return "not-ajax-01";
    }
    @RequestMapping("/doNotAjaxStart")
    public String doNotAjaxStart(Model model){
        model.addAttribute("result", "do not ajax request result");
        return "not-ajax-01";//请问这是局部刷新，还是全局
    }
    //============Ajax方式的请求===================
    @ResponseBody
    @RequestMapping("/doAjaxStart")
    public String doAjaxStart(){
        return "Response Result Of Ajax Get Request 01";
    }
}
